package cc.mrbird.febs.common.validator;

import cc.mrbird.febs.common.annotation.IsRightFormat;
import cc.mrbird.febs.common.enums.FormatType;
import org.apache.commons.lang3.StringUtils;
import org.quartz.CronExpression;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 校验是否为合法的 格式
 */
public class FormatValidator implements ConstraintValidator<IsRightFormat, String> {

    private FormatType type;

    @Override
    public void initialize(IsRightFormat isRightFormat) {
        type = isRightFormat.type();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        try {
            if((FormatType.ID_CARD.equals(type)) && (StringUtils.isNotBlank(value))) {
                String id_18 = "^[1-9][0-9]{5}(18|19|20)[0-9]{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)[0-9]{3}([0-9]|(X|x))";
                String id_15 = "^[1-9][0-9]{5}[0-9]{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)[0-9]{2}[0-9]";
                String id_valid = "(" + id_18 + ")" + "|" + "(" + id_15 + ")";
                Pattern pattern = Pattern.compile(id_valid);
                Matcher matcher = pattern.matcher(value);
                return matcher.matches();
            } else if((FormatType.MOBILE.equals(type)) && (StringUtils.isNotBlank(value))) {
                String regex = "(^0\\d{2,3}-\\d{7,8}$)|(^[1]\\d{10}$)";
                Pattern p = Pattern.compile(regex);
                Matcher m = p.matcher(value);
                return m.matches();
            } else {
                return true;
            }
        } catch (Exception e) {
            return false;
        }
    }
}